package com.attilax.io;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import com.attilax.collection.ACollections;
import com.attilax.json.AtiJson;
import com.attilax.lang.Closure;
import com.attilax.math.ANum;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

import static com.attilax.linq.LinqBuilder.*;

public class AFile {

	private String encode;
	private String path;

	public AFile(String p, String e) {
		path = p;
		encode = e;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
	//	4>1,7>2,11>3,13>4
		//dir 2>2,  5>3,9>4, 13>5 17>6   20>7
		String start = "c:\\myoa";
		String dirFlagChar="└├─";
		final String dirFlagChar1="─";
		AFile f = new AFile("c:\\myoa\\tree.txt", "gbk");
		final Set st=Sets.newConcurrentHashSet();
		f.trave(new Closure<String, Object>() {

			@Override
			public Object execute(String line) throws Exception {
				if(line.contains(dirFlagChar1))
				{
				int id = line.indexOf(dirFlagChar1)+1;
			 st.add(id);
				String idex=new ANum(	id).toStr();
				if(id>60)
			 System.out.println(idex+":"+line);
				}
				return null;
			}
		});
		List li= Lists.newArrayList();
			li	.addAll(st);
 		Collections.sort(li);
		 //	List li2=
		 			//from(li).orderby().exe();
			
				//ACollections.set2list(st);
		System.out.println(AtiJson.toJson(li));
		System.out.println("--f");
	}

	void trave(Closure<String, Object> closure) {
		if (path.equals("")) {
			System.out.println("--warnging :  path is empty cad");return;
			// return new ArrayList<String>();
		}
		InputStreamReader isr;

		// BufferedWriter writer = new BufferedWriter(new FileWriter(dest));
		String line;
		BufferedReader reader;
		try {
			isr = new InputStreamReader(new FileInputStream(path), encode);

			reader = new BufferedReader(isr);
			line = reader.readLine();
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			throw new RuntimeException(e1);
		}
		while (line != null) {

			try {
				closure.execute(line);
			} catch (Exception e) {
				// attilax 老哇的爪子 4:24:05 AM Aug 3, 2014
				e.printStackTrace();
			}
			try {
				line = reader.readLine();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		try {
			reader.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
